package com.android.manghe.common.webview;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Service;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.JsResult;
import android.webkit.ValueCallback;
import android.webkit.WebBackForwardList;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.android.base.frame.presenter.IView;
import com.android.base.frame.presenter.XPresenter;
import com.android.base.frame.title.ETitleType;
import com.android.base.frame.view.MVPFragment;
import com.android.manghe.R;
import com.android.manghe.cache.StatusHolder;
import com.android.manghe.cache.UserHolder;
import com.android.manghe.common.activity.PaySuccessActivity;
import com.android.manghe.common.model.WebViewUserInfo;
import com.android.manghe.config.Config;
import com.android.manghe.mine.model.UserRes;
import com.android.manghe.utils.MoneyUtil;
import com.android.manghe.view.crop.ImageCropHelper;
import com.fm.openinstall.OpenInstall;
import com.google.gson.Gson;
import com.isseiaoki.simplecropview.CropImageView;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import me.nereo.multi_image_selector.MultiImageSelector;
import me.nereo.multi_image_selector.MultiImageSelectorActivity;

/**
 * Created by lindan on 18-1-13.
 * 用于嵌入Activity的WebViewFragment，浏览H5页面
 */
public class WebViewFragment extends MVPFragment<XPresenter<IView>> implements SwipeRefreshLayout.OnRefreshListener {
    private SwipeRefreshLayout swipeRefreshLayout;
    private WebView webView;
    private View errorView, refreshView;
    private WebViewEventListener listener;
    private WebViewParameter parameter;
    private JsInteraction jsInteraction;//js调用java交互类
    private boolean needKeyboardHandle = false;//是否需要处理WebView中的输入框导致键盘遮挡问题

    private ValueCallback<Uri[]> uploadFiles;

    @Override
    protected ETitleType showToolBarType() {
        return ETitleType.NO_TITLE;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle arguments = getArguments();
        if (arguments == null) {
            throw new IllegalArgumentException("you must give the parameters");
        }
        parameter = (WebViewParameter) arguments.getSerializable("parameter");
        if (parameter == null) {
            throw new IllegalArgumentException("you must give the parameters");
        }
    }

    @Override
    protected void initData(@androidx.annotation.Nullable Bundle savedInstanceState, View parent) {

    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        if (needKeyboardHandle) {
//            AndroidBug5497Workaround.assistFragment(this,
//                    DensityUtil.dp2px(ContextHolder.getContext(), 46));
        }
        initViews(view);
        initListeners();
        if (parameter.getCookieMap().size() != 0) {
            //同步Cookie,必须在loadUrl之前调用，H5页面才能获取到
            syncCookie(parameter.getCookieMap(), false);
        }
        if(parameter.getUrl()!=null){
            loadUrl(parameter.getUrl());
        }else if(parameter.getHtmUrl()!=null){
            loadHtml(parameter.getHtmUrl());
        }
    }

    @SuppressLint({"SetJavaScriptEnabled", "AddJavascriptInterface"})
    private void initViews(View view) {
        errorView = view.findViewById(R.id.web_view_error_layout);
        refreshView = view.findViewById(R.id.refresh_btn);
        swipeRefreshLayout = view.findViewById(R.id.swipe_refresh_layout);
        swipeRefreshLayout.setColorSchemeResources(R.color.colorPrimary);
        webView = view.findViewById(R.id.web_view);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            WebView.setWebContentsDebuggingEnabled(true);
        }
        WebSettings settings = webView.getSettings();
        settings.setJavaScriptEnabled(true);//允许运行JS脚本
        settings.setDomStorageEnabled(true);
        settings.setDefaultTextEncodingName("utf-8");//设置编码
//        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);//适应屏幕
        settings.setUseWideViewPort(true);
        settings.setLoadWithOverviewMode(true);
        String customUserAgent = parameter.getCustomUserAgent();
        boolean append = parameter.isAppendCustomUserAgent();
        settings.setUserAgentString(settings.getUserAgentString() + "android");//设置UA
        if (!TextUtils.isEmpty(customUserAgent)) {
            settings.setUserAgentString(append ? settings.getUserAgentString() + customUserAgent : customUserAgent);
        }
        settings.setJavaScriptCanOpenWindowsAutomatically(true);//允许JS弹窗
        //设置允许web上的存储
        settings.setDomStorageEnabled(true);
        settings.setDatabaseEnabled(true);
        settings.setAllowFileAccess(true);
        settings.setAppCacheEnabled(false);
        settings.setCacheMode(WebSettings.LOAD_NO_CACHE);

        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
            webView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        webView.getSettings().setBlockNetworkImage(false);

        if (jsInteraction == null) {
            jsInteraction = new JsInteraction(getActivity(), this.listener);
        }
        webView.addJavascriptInterface(jsInteraction, "app");//设置供JS调用的接口
        //webView.addJavascriptInterface(jsInteraction, "check_balance");//设置供JS调用的接口
        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                if (listener != null) {
                    listener.onProgressChange(newProgress);
                }
            }

            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
                if (listener != null && !title.contains("/")) {//web页面加载过程中title会先返回url地址
                    listener.onReceivedTitle(title);
                }
            }

            @Override
            public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
                return super.onJsAlert(view, url, message, result);
            }

            @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
            public boolean onShowFileChooser(WebView mWebView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
                WebViewFragment.this.uploadFiles = filePathCallback;
                MultiImageSelector.create()
                        .showCamera(true) // show camera or not. true by default
                        .single() // multi mode, default mode;
                        .start(getActivity(), 1000);
                return true;
            }
        });
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (listener != null) {
                    if (listener.shouldOverrideUrlLoading(url)) {
                        return true;
                    }
                }
                view.loadUrl(url);
                return true;
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                if (swipeRefreshLayout.isRefreshing()) {
                    swipeRefreshLayout.setRefreshing(false);
                }
                if (listener != null) {
                    listener.onPageFinished(view, url);
                }
//                UserRes.UserInfo userInfo = UserHolder.getUserInfo(getActivity());
//                if (userInfo == null) {
//                    getActivity().finish();
//                    open(LoginActivity.class);
//                } else {
//                    String jsonUser = new Gson().toJson(new WebViewUserInfo(userInfo.TOKEN, userInfo.UID, userInfo.UNAME, userInfo.avatar));
//                    javaCallJs("callJS", jsonUser);
//                }
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                UserRes.UserInfo userInfo = UserHolder.getUserInfo(getActivity());
                if (userInfo == null) {
                    super.onPageStarted(view, url, favicon);
                    if (listener != null) {
                        listener.onPageStarted(url, favicon);
                    }
                    if (parameter.isReloadable() && parameter.getReloadType() == ERefreshWebType.ClickRefresh) {
                        //上一次页面加载失败,并且设置的刷新方式是点击按钮刷新
                        errorView.setVisibility(View.GONE);
                        swipeRefreshLayout.setVisibility(View.VISIBLE);
                    }
                } else {
                    String jsonUser = new Gson().toJson(new WebViewUserInfo(userInfo.TOKEN, userInfo.UID, userInfo.UNAME, userInfo.avatar));
                    String js = "window.localStorage.setItem('user','" + jsonUser + "');";
                    String jsUrl = "javascript:localStorage.setItem('user','" + jsonUser + "');";
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                        view.evaluateJavascript(js, null);
                    } else {
                        view.loadUrl(jsUrl);
                    }
                }
                if (!TextUtils.isEmpty(url) && url.contains("/home/shengfupay_success")) {
                    TelephonyManager tm = (TelephonyManager) getActivity().getSystemService(Service.TELEPHONY_SERVICE);
//                    TuiAManager.send(getActivity(), MD5.md5(tm.getDeviceId()), 6);
                    OpenInstall.reportEffectPoint(Config.OpenInstall_Voucher, MoneyUtil.changeY2F(StatusHolder.mCurrentVoucherPrice));

                    Map<String, String> map_value = new HashMap<>();
                    map_value.put("charge", "1");
                    MobclickAgent.onEventValue(getActivity(), "charge", map_value, MoneyUtil.changeY2F(StatusHolder.mCurrentVoucherPrice));


                    //PayTrack
                    try {
                        Map successPayMap = new HashMap();
                        successPayMap.put("userid", UserHolder.getUID(getActivity()));
                        successPayMap.put("orderid", System.currentTimeMillis());
                        successPayMap.put("item", "购券");
                        successPayMap.put("amount", MoneyUtil.changeY2F(StatusHolder.mCurrentVoucherPrice));
                        MobclickAgent.onEvent(getActivity(), "__finish_payment", successPayMap);
                    } catch (Exception e) {

                    }

                    getActivity().finish();
                    open(PaySuccessActivity.class);
                }

                super.onPageStarted(view, url, favicon);
                if (listener != null) {
                    listener.onPageStarted(url, favicon);
                }
                if (parameter.isReloadable() && parameter.getReloadType() == ERefreshWebType.ClickRefresh) {
                    //上一次页面加载失败,并且设置的刷新方式是点击按钮刷新
                    errorView.setVisibility(View.GONE);
                    swipeRefreshLayout.setVisibility(View.VISIBLE);
                }
            }

            /**
             * android 6.0 或之后版本会被调用
             */
            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
//                if (listener != null) {
//                    listener.onLoadError();
//                }
//                dealError();
            }

            /**
             * android6.0之前会被调用
             */
            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
//                if (listener != null) {
//                    listener.onLoadError();
//                }
//                //在6.0之后的版本也会被调用，所以加在判断，不要跟新版本的onReceivedError重复调用
//                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//                    return;
//                }
//                dealError();
            }
        });
    }


    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == 1000) {
                ArrayList<String> arrayList = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
                if (arrayList != null && !arrayList.isEmpty()) {
                    ImageCropHelper.startCropFree(
                            getActivity(), arrayList.get(0),
                            ImageCropHelper.ImageCropParamsBuilder
                                    .create()
                                    .compressQuality(90)
                                    .cropMode(CropImageView.CropMode.FREE)
                                    .build(), 1001
                    );
                }

            } else if (requestCode == 1001) {
                Uri resultUri = ImageCropHelper.onActivityResult(resultCode, data);
                if (resultUri != null) {
//                    String imagePath = MediaUtil.getPath(getActivity(), resultUri);
                    if (WebViewFragment.this.uploadFiles != null) {
                        WebViewFragment.this.uploadFiles.onReceiveValue(new Uri[]{resultUri});
                    }
                }
            }
        }

    }

    private void dealError() {
        if (parameter.isReloadable() && parameter.getReloadType() == ERefreshWebType.ClickRefresh) {
            //加载失败,并且设置的刷新方式是点击按钮刷新
            errorView.setVisibility(View.VISIBLE);
            swipeRefreshLayout.setVisibility(View.GONE);
        }
    }




    private void initListeners() {
        refreshView.setOnClickListener(view -> webView.reload());
        if (parameter.isReloadable() && parameter.getReloadType() == ERefreshWebType.DragRefresh) {
            swipeRefreshLayout.setEnabled(true);
            swipeRefreshLayout.setOnRefreshListener(this);
        } else {
            swipeRefreshLayout.setEnabled(false);
            swipeRefreshLayout.setOnRefreshListener(null);
        }
    }

    @Override
    public void onRefresh() {
        swipeRefreshLayout.setRefreshing(true);
        webView.reload();
    }


    /**
     * 浏览历史是否能后退
     */
    public boolean canGoBack() {
        return webView.canGoBack();
    }

    /**
     * 浏览历史是否能前进
     */
    public boolean canGoForward() {
        return webView.canGoForward();
    }

    /**
     * 浏览历史后退
     */
    public void back() {
        if (webView.canGoBack()) {
            webView.goBack();
        }
    }

    /**
     * 指定步长跳转历史记录
     *
     * @param step 步长
     */
    public void backOrForward(int step) {
        if (webView.canGoBackOrForward(step)) {
            webView.goBackOrForward(step);
        }
    }

    /**
     * 获取浏览历史记录大小
     */
    public int getHistoryListSize() {
        WebBackForwardList list = webView.copyBackForwardList();
        if (list == null) {
            return 0;
        }
        return list.getSize();
    }

    /**
     * 浏览历史前进
     */
    public void forward() {
        if (webView.canGoForward()) {
            webView.goForward();
        }
    }

    public void resume() {
        if (webView != null) {
            webView.onResume();
        }
    }

    public void pause() {
        if (webView != null) {
            webView.onPause();
        }
    }

    public void destroy() {
        if (webView != null) {
            webView.destroy();
        }
        clearCookie();
    }

    /**
     * 将cookie同步到WebView
     */
    public void syncCookie(HashMap<String, String> cookieMap, boolean isReload) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            CookieSyncManager.createInstance(getActivity());
        }
        CookieManager cookieManager = CookieManager.getInstance();
        for (Map.Entry<String, String> entry : cookieMap.entrySet()) {
            cookieManager.setCookie(entry.getKey(), entry.getValue());
        }
        if (isReload) {
            webView.reload();
        }
    }

    /**
     * 清理Cookie
     */
    private void clearCookie() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            CookieSyncManager.createInstance(getActivity());
        }
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.removeAllCookie();
    }

    /**
     * Java调用js方法
     *
     * @param methodName JS方法名
     * @param jsonStr    返回给JS的Json
     */
    @TargetApi(Build.VERSION_CODES.KITKAT)
    public void javaCallJs(String methodName, String jsonStr) {
        //调用JS方法必须在UI线程执行
        webView.post(() -> {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                //Android4.4以上
                webView.evaluateJavascript(methodName + "(" + jsonStr + ")", value -> {
                            //这个回调暂时用不上
                        }
                );
            } else {
                loadUrl("javascript:" + methodName + "(" + jsonStr + ")");
            }
        });
    }

    /**
     * 设置WebView事件监听器
     */
    public void setWebViewEventListener(WebViewEventListener webViewEventListener) {
        this.listener = webViewEventListener;
    }

    public static WebViewFragment newInstance(WebViewParameter parameter, WebViewEventListener webViewEventListener) {
        WebViewFragment fragment = new WebViewFragment();
        fragment.setWebViewEventListener(webViewEventListener);
        Bundle args = new Bundle();
        args.putSerializable("parameter", parameter);
        fragment.setArguments(args);
        return fragment;
    }

    public void loadUrl(String url) {
        webView.loadUrl(url);
    }

    public void loadHtml(String ulr) {
        webView.loadData(ulr, "text/html", "utf-8");
    }

    public void setNeedKeyboardHandle(boolean needKeyboardHandle) {
        this.needKeyboardHandle = needKeyboardHandle;
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_webview;
    }
}
